package com.jfinal_demo.app.authenticate;

import javax.servlet.http.HttpSession;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal_demo.app.DataWrapper;


public class AuthenticateInterceptor implements Interceptor {
    public void intercept(Invocation invocation) {
        boolean needAuthenticate = false;
        Authenticate methodAnnotation = invocation.getMethod().getAnnotation(Authenticate.class);
        Authenticate targetClassAnnotation = invocation.getTarget().getClass().getAnnotation(Authenticate.class);
        if (targetClassAnnotation != null) {
            needAuthenticate = targetClassAnnotation.value();
        }
        if (methodAnnotation != null) {
            needAuthenticate = methodAnnotation.value();
        }
        if (needAuthenticate) {
            if (!invocation.isActionInvocation())
                throw new RuntimeException("com.jfinal_demo.app.authenticate.Authenticate");
            Controller controller = invocation.getController();
            HttpSession session = controller.getSession();
            if (session == null || session.getAttribute(LoginInfo.SESSION_KEY) == null) {
                controller.renderJson(DataWrapper.fail("Please login to the website"));
                return;
            }
        }

        invocation.invoke();
    }
}
